package com.wj.activiti.interceptor;

import org.activiti.engine.*;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.Picture;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {

    public static void main(String[] args) throws IOException {
        // 创建activiti配置对象
        ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration
                .createProcessEngineConfigurationFromResource("my-config.xml");

        // 初始化流程引擎
        ProcessEngine engine = processEngineConfiguration.buildProcessEngine();

//        // 部署流程
//        engine.getRepositoryService().createDeployment().addClasspathResource("bpmn/First.bpmn").deploy();

//        // 构建流程参数
//        Map<String, Object> vars = new HashMap<>();
//        vars.put("day", 10);

//        // 开始流程
//        engine.getRuntimeService().startProcessInstanceByKey("process1", vars);

//        TaskService taskService = engine.getTaskService();
//        // 查询第一个任务
//        Task task = taskService.createTaskQuery().singleResult();
//        System.out.println("第一个任务完成前，当前任务名称：" + task.getName());
//        // 完成第一个任务
//        taskService.complete(task.getId());
//        // 查询第二个任务
//        task = taskService.createTaskQuery().singleResult();
//        System.out.println("第二个任务完成前，当前任务名称：" + task.getName());
//        // 完成第二个任务（流程结束）
//        taskService.complete(task.getId());
//        task = taskService.createTaskQuery().singleResult();
//        System.out.println("流程结束后，查找任务：" + task);
//        // 退出
//        System.exit(0);

//        IdentityService identityService = engine.getIdentityService();

//        createGroup(identityService, "1", "GroupA", "TypeA");
////        createGroup(identityService, "2", "GroupB", "TypeB");
////        createGroup(identityService, "3", "GroupC", "TypeC");
////        createGroup(identityService, "4", "GroupD", "TypeD");
////        createGroup(identityService, "5", "GroupE", "TypeD");

//        createUser(identityService, "1", "l", "ll", "wwww", "123");
//        createUser(identityService, "2", "w", "ww", "wwww", "123");
//        createUser(identityService, "3", "s", "ss", "wwww", "123");
//
//        identityService.createMembership("1", "1");
//        identityService.createMembership("2", "2");
//        identityService.createMembership("3", "4");

//        identityService.setUserInfo("1", "age", "20");
//        identityService.setAuthenticatedUserId("2");

        //读取图片并转换为 byte 数组
//        File file = new File("picture.png");
//        FileInputStream fis =new FileInputStream (file) ;
//        BufferedImage img = ImageIO.read(fis) ;
//        ByteArrayOutputStream output= new ByteArrayOutputStream();
//        ImageIO.write(img,  "png", output) ;
//        //读取图片的 byte 数组
//        byte[] picArray = output.toByteArray();
//        //创建Picture 实例
//        Picture picture= new Picture(picArray, "angus image");
//        //为用户设直图片
//        identityService .setUserPicture("1", picture);

//        List<Group> groupList = identityService.createGroupQuery().list();
//        for(Group group : groupList) {
//            System.out.println(group.getId() + "---" + group.getName());
//        }

//        List<User> userList = identityService.createUserQuery().memberOfGroup("1").list();
//        for(User user : userList) {
//            System.out.println(user.getId() + "---" + user.getFirstName() + "---" + user.getLastName() + "---" + user.getEmail());
//            System.out.println("age: " +  identityService.getUserInfo("1", "age"));
//            System.out.println(Authentication.getAuthenticatedUserId());
//            Picture picture1 = identityService.getUserPicture("1");
//            System.out.println(picture1);
//        }

//        RepositoryService repositoryService = engine.getRepositoryService();
//        List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().processDefinitionKey("process1").list();
//
//        for(ProcessDefinition processDefinition : processDefinitions) {
//            repositoryService.addCandidateStarterGroup(processDefinition.getId(), "1");
//        }

//        RepositoryService repositoryService = engine.getRepositoryService();
//        //得到身份服务组件
//        IdentityService identityService = engine.getIdentityService ();
//        //部署流程描述文件
//        Deployment dep = repositoryService.createDeployment().addClasspathResource("bpmn/candidateUser.bpmn").deploy();
//        //添加两个用 户
//        createUser(identityService, "user1", "张三", "张三", "mail1", "123");
//        createUser(identityService, "user2", "李四", "李四", "mail2", "1234");
//        //添加两个用户组
//        createGroup(identityService, "group1", "经理组", "manager");
//        createGroup(identityService, "group2", "员工组", "employee");
//        //查询流程定义
//        ProcessDefinition def = repositoryService
//                .createProcessDefinitionQuery().deploymentId (dep.getId()).singleResult();
//        //设置权限数据
//        repositoryService.addCandidateStarterGroup(def.getId(), "group1");
//        repositoryService.addCandidateStarterGroup(def.getId(), "group2");
//
//        repositoryService.addCandidateStarterUser(def.getId(), "user1");
//        repositoryService.addCandidateStarterUser(def.getId(), "user2");
//
//        List<ProcessDefinition> defs = repositoryService.createProcessDefinitionQuery().startableByUser("user1").list();
//
//        System.out.println("用户张三有权限的流程定义为 :"); //结果为 1
//        for (ProcessDefinition dft : defs) {
//            System.out.println("  " + dft.getName());
//        }
//
//        //根据流程定义查询用户组数据
//        List<Group> groups = identityService.createGroupQuery().potentialStarter(def.getId()).list();
//        System.out.println ("以下用户组对流程定义有权限 :") ;
//        for (Group group : groups) {
//            System.out.println("  " + group.getName());
//        }
//
//        //根据流程定义查询用户数据
//        List<User> users = identityService.createUserQuery().potentialStarter(def.getId()).list();
//        System.out.println("以下用户对流程定义有权限 :"); //结果为 2
//        for (User user : users) {
//            System.out.println("  " + user.getFirstName());
//        }
//
//        //根据流程定义查询全部的 Identi tyLink (ACT_RU_IDENTITYLINK 表〉 数据
//        List<IdentityLink> links = repositoryService.getIdentityLinksForProcessDefinition(def.getId());
//        System.out.println("与流程定义相关的数据量: " + links.size());//结果为4

//        RepositoryService repositoryService = engine.getRepositoryService();
//        List<Deployment> deps = repositoryService.createDeploymentQuery().list();
//        for(Deployment dep : deps) {
//            repositoryService.deleteDeployment(dep.getId(), true);
//        }

        //获取任务服务组件
        TaskService taskService = engine.getTaskService();
//        //保存若干个 Task
//        for (int i = 1; i < 10; i++) {
//            saveTask(taskService, String.valueOf(i));
//        }
//        //删除 task (不包括历史数据和子任务)
//        taskService.deleteTask("1");
//        // 删除 task (包括历史数据和子任务)
//        taskService.deleteTask("2", true);
//        // 删除多个 task (不包括历史数据和子任务)
//        List<String> ids = new ArrayList<>();
//        ids.add("3");
//        ids.add("4");
//        taskService.deleteTasks(ids);
//        //删除多个 task (包括历史数据和子任务〉
//        ids = new ArrayList<>();
//        ids.add("5");
//        ids.add("6");
//        taskService.deleteTasks(ids, true);
//        //再删除 ID 为 3 的 task，此时任务 3 的历史数据也会被删除
//        taskService.deleteTask("3", true);


//        Task task1 = taskService . newTask ("taskl");
//        taskService . saveTask(task1);
//        //保存第二个 Task
//        Task task2 = taskService.newTask ("task2") ;
//        taskService.saveTask(task2) ;
//        //绑定用户组与任务的关系
//        taskService.addCandidateGroup("taskl", "group1");
//        taskService.addCandidateGroup("task2", "group1");

        RepositoryService repositoryService = engine.getRepositoryService();

//        Deployment dep = repositoryService.createDeployment().addClasspathResource("bpmn/localVariable.bpmn20.xml").deploy();
//
//        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(dep.getId())
//                .singleResult();

//
//        Map<String, Object> vars = new HashMap<>();
//        vars.put("days", 5);
//
        RuntimeService runtimeService = engine.getRuntimeService();
        runtimeService.startProcessInstanceByKey("vacationRequest");
//
//        long count = runtimeService.createProcessInstanceQuery().count();
//        System.out.println("流程实例数量：" + count);



    }

    static void createGroup (IdentityService identityService, String id, String name, String type){
        Group group = identityService.newGroup(id);
        group.setName(name);
        group.setType(type);
        identityService.saveGroup(group);
    }

    static void createUser (IdentityService identityService, String id, String firstName, String lastName, String
            email,
                            String password){
        User user = identityService.newUser(id);
        user.setFirstName(firstName);
        user.setLastName(lastName);
        user.setEmail(email);
        user.setPassword(password);
        identityService.saveUser(user);
    }

    //保存一个 task
    static void saveTask(TaskService taskService, String id){
        Task task = taskService.newTask(id);
        taskService.saveTask(task);
    }
}
